import { defineStore } from 'pinia'
import { Router } from '@/router'
import { loginAPI, loginAppAPI, logout } from '@/assets/api/login'
import { removeToken, setToken } from '@/utils/auth'
import { getInfoAPI } from '@/assets/api/app'
import useUser from '@/store/user'
import dayjs from 'dayjs'

const useApp = defineStore('app', {
  state: () => {
    return {
      token: null,
      getInfoFinish: false,
      // 是否自动登录
      automaticLogon: false,
      // 记住密码
      rememberPassword: false,
      // 消息发送方式
      sendShortcutKey: 1,
      // 此服务时间30s更新一次,不可用于显示使用
      serverTime: dayjs().valueOf(),
      // 服务器时间差
      timeDiff: 0,
      // im websocket
      imWebsocket: null,
      // App 是否在桌面最前端
      appIsFocus: true,
    }
  },
  persist: [
    {
      storage: sessionStorage,
      paths: ['token'],
    },
    {
      paths: ['automaticLogon', 'rememberPassword', 'sendShortcutKey'],
    },
  ],
  getters: {
    // 当前时间 ms
    currentTime(state) {
      return dayjs().valueOf() + state.timeDiff
    },
  },
  actions: {
    setAppIsFocus(v) {
      this.appIsFocus = v
    },
    setImWebsocket(ws) {
      this.imWebsocket = ws
    },
    setServerTime(time) {
      this.serverTime = time
      this.timeDiff = time - dayjs().valueOf()
    },
    setAutomaticLogon(v) {
      this.automaticLogon = v
      if (v) {
        this.setRememberPassword(true)
      }
    },
    setRememberPassword(v) {
      this.rememberPassword = v
      if (!v) {
        this.setAutomaticLogon(false)
      }
    },
    setToken(token) {
      setToken(token)
      this.token = token
    },
    setSendShortcutKey(sendShortcutKey) {
      this.sendShortcutKey = sendShortcutKey
    },
    login(data) {
      return login(data)
    },
    loginOut() {
      logout().then(() => {
        this.setToken(null)
        localStorage.clear()
        sessionStorage.clear()
        this.setAutomaticLogon(false)
        removeToken()
        location.reload()
      })
    },
  },
})

async function login(params) {
  return new Promise((resolve, reject) => {
    loginAPI(params)
      .then((res) => {
        if (res.code === 200) {
          const appStore = useApp()
          appStore.setToken(res.data.access_token)
          resolve()
        } else {
          reject(res.massage || res.msg)
        }
      })
      .catch(() => {
        reject('网络错误')
      })
  })
}

export function getInfo(params) {
  return new Promise((resolve, reject) => {
    getInfoAPI(params).then((res) => {
      if (res.code === 200) {
        const appStore = useApp()
        const userStore = useUser()
        if (res.data.routers) {
          handleRouter(res.data.routers, res.data.apps)
        }
        if (res.data.user) {
          userStore.setUserInfo(res.data.user)
        }

        appStore.getInfoFinish = true
        resolve()
      } else {
        reject(res.message)
      }
    })
  })
}

function handleRouter(routers, apps, add = false) {
  routers.forEach((i) => {
    if (i.component) {
      const name = i.component
      i.component = () => import(`@/views/${name}.vue`)
    } else {
      i.component = () => import(`@/views/chat/Chat.vue`)
    }
    if (i.meta && i.meta.belongAppId !== null) {
      if (i.meta.isOwner === '1') {
        const app = apps.find((j) => j.uid === i.meta.belongUId)
        i.name = (app.activeRule || '') + i.path
        i.path = (app.activeRule || '') + i.path
      }
    }
    if (i.children) {
      handleRouter(i.children, apps, true)
    } else {
      Router.addRoute('Layout', i)
    }
    if (add) {
      Router.addRoute('Layout', i)
    }
  })
}

export default useApp
